package com.st.controller.background;

import com.st.entity.Admin;
import com.st.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private IAdminService adminService;

    @RequestMapping("/query")
    public ModelAndView query(Admin admin) {
        ModelAndView mv = new ModelAndView();
        List<Admin> list = adminService.query(admin);
        mv.addObject("list", list);
        mv.setViewName("/background/admin");
        return mv;
    }

    @RequestMapping("/add")
    @ResponseBody
    public String add(Admin admin) {
       List<Admin> list= adminService.query(admin);
       if (list==null || list.size()==0) {
           String pass = "123";
           //md5加密和加盐处理
           String md5Pass2 = String.valueOf(DigestUtils.appendMd5DigestAsHex(pass.getBytes(StandardCharsets.UTF_8), new StringBuilder("wzf")));
           String md5Pass = DigestUtils.md5DigestAsHex(md5Pass2.getBytes(StandardCharsets.UTF_8));
           admin.setPassword(md5Pass);
           int count = adminService.add(admin);
           if (count == 1) {
               return "1";
           } else return "0";
       }return "3";
    }

    @RequestMapping("del")
    @ResponseBody
    public String del(Integer id) {
        int count = adminService.del(id);
        if (count == 1) {
            return "1";
        } else return "0";
    }

    @RequestMapping("toUpdate")
    public ModelAndView toUpdate(Admin admin) {
        ModelAndView mv = new ModelAndView();
        List<Admin> list = adminService.query(admin);
        mv.addObject("list", list.get(0));
        mv.setViewName("/background/update");
        return mv;
    }

    @RequestMapping("update")
    @ResponseBody
    public String update2(Admin admin) {
        if (admin.getPassword().length() != 32) {
            //md5加密和加盐处理
            String md5Pass2= String.valueOf(DigestUtils.appendMd5DigestAsHex(admin.getPassword().getBytes(StandardCharsets.UTF_8), new StringBuilder("wzf")));
            String md5Pass = DigestUtils.md5DigestAsHex(md5Pass2.getBytes(StandardCharsets.UTF_8));
            admin.setPassword(md5Pass);
        }
        int count = adminService.update(admin);
        if (count == 1) {
            return "1";
        } else return "0";
    }


}
